package carcassonne.server.websocket;

import carcassonne.server.websocket.handler.GateHandler;
import carcassonne.server.websocket.handler.WebSocketRequestHandler;
import carcassonne.server.websocket.handler.HearBeatHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class WebsocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline pipeline = socketChannel.pipeline();

        // 添加一个http的编解码器
        pipeline.addLast(new HttpServerCodec());
        // 添加一个用于支持大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        // 添加一个聚合器，这个聚合器主要是将HttpMessage聚合成FullHttpRequest/Response
        pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
        // 需要指定接收请求的路由
        pipeline.addLast(new GateHandler());
        // 必须使用以ws后缀结尾的url才能访问
        pipeline.addLast(new WebSocketServerProtocolHandler("/carcassonne"));
        // 添加自定义的Handler
        pipeline.addLast(new WebSocketRequestHandler());

        pipeline.addLast(new IdleStateHandler(10, 20, 60));
        pipeline.addLast(new HearBeatHandler());
    }
}